package Service;

import DAO.BookDAO;
import DAO.CommentDAO;
import DAO.UserDAO;
import DATA.Book;
import DATA.Comment;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "getBook2", value = "/getBook2")
public class getBook2 extends HttpServlet {
    //接受从addComment传过来的，就为了插入数据后能重新定位到这里，我把getBook几乎复制了一份放在这里
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int bookid= (int) req.getAttribute("bid");
        try {
            Book book=BookDAO.FindbyID(bookid);
            req.setAttribute("bookName", book.getBookName());
            req.setAttribute("bookType", book.getBookType());
            req.setAttribute("author", book.getAuthor());
            req.setAttribute("recommend",book.getRecommend());
            req.setAttribute("bid", book.getId());
            try {
                List<Comment> comments= CommentDAO.findByBookID(book.getId());
                Iterator<Comment> commentsIterator = comments.listIterator();
                ArrayList<muchInfo> commentsList = new ArrayList();//就为了三个数，我要手动建了一个新类来传

                while (commentsIterator.hasNext()) {
                    Comment aComment = commentsIterator.next();
                    commentsList.add(new muchInfo(new UserDAO().FindbyId(aComment.getuId()).getUsername(),aComment.getContent(),aComment.getWhich()));
                }
                req.setAttribute("comments", commentsList);

                req.getRequestDispatcher("BookDetail.jsp").forward(req, resp);

            } catch (SQLException e) {
                throw new RuntimeException(" 找评论失败");
            }

        } catch (SQLException e) {
            throw new RuntimeException("找书失败");
        }
    }
}
